from django.shortcuts import render,redirect
from django.http import JsonResponse,HttpResponseRedirect
from django.contrib.auth.hashers import make_password,check_password
from django.core.paginator import Paginator

from .models import UserModel
from .forms import UserRegisterForm,UserLoginForm
from .utils import login_required
from goods.models import GoodsModel
from order.models import OrderModel

# Create your views here.


def register_post(request):
    """只接受POST注册接口"""
    if request.method =='POST':
        user = UserLoginForm(request.POST)
        if not user.is_valid():
            return JsonResponse(user.errors.get_json_data(),safe=False)
    user = UserLoginForm()
    return render(request,'user/register_post.html',{'user':user})
def register(request):
    """注册接口"""
    cookie = request.COOKIES
    if request.method =='POST':
        # 忽略参数为空的情况
        username = request.POST.get('username','')
        if not username:
            return JsonResponse({'error':'请输入用户名'})
        password = request.POST.get('password','')
        phone = request.POST.get('phone','')
        address = request.POST.get('address','')
        email = request.POST.get('email','')

        """创建新用户"""
        user = UserModel()
        user.username = username
        """密码加密后储存"""
        user.password = make_password(password)
        user.phone = phone
        user.address = address
        user.email = email
        user.save()
        return render(request, "user/login.html")
    return render(request,"user/register.html")

def login (request):
    """登录接口"""
    if request.method == 'POST':
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        # 当jizhu有值的时候，就是复选框被勾选的时候的值1，没有的话是0
        jizhu = request.POST.get('jizhu',0)
        # 根据用户名查用户对象
        user = UserModel.objects.filter(username = username)
        # 判断，如果没有查到用户，说明用户名错误，如果查到则判断是否正确
        # 密码错误：返回登陆页面，并显示错误信息
        if user:
            user = user[0]
            # 检查密码是否正确
            is_password = check_password(password,user.password)
            if not is_password:
                # """密码错误 """
                return render(request,'user/login.html',{'username':username,'is_password':1,'is_user':0})
            else:
                # """密码正确"""
                # 先生成response对象info
                next_url = request.COOKIES.get('next_url','/account/info')
                response = HttpResponseRedirect(next_url)
                # 记住用户名

                # 设置cookie
                if jizhu !=0:
                    response.set_cookie('username',username)
                else:
                    # max_age指的是过期时间 当值为-1时为立即过期
                    response.set_cookie('username','',max_age=-1)
                    # 把用户id和username放入到session中
                    request.session["user_id"] = user.id
                    request.session['username'] = username
                    return response
        # """用户不存在"""
        else:
            return render(request,'user/login.html',{'username':username,'is_user':1,'is_password':0})
    # get请求
    return render(request,'user/login.html')

# 退出登录
def logout(request):
    del request.session['user_id']
    del request.session['username']
    return redirect("/account/login")

# 装饰器
@login_required
def info(request):
    # 用户个人信息
    user_id =request.session["user_id"]
    user = UserModel.objects.get(id=user_id)
    user_info = {
        "username":user.username,
        "phone":user.phone,
        "address":user.address
    }
    # 从session中拿到商品的id列表（在商品详情里写入session的）
    goods_id_list = request.session.get(str(user_id),[])
    # 用户最近商品的浏览记录
    goods_list = []
    # 同步便利商品
    for goods_id in goods_id_list:
        goods_list.append(GoodsModel.objects.get(id=goods_id))
    context = {
        "user_info":user_info,
        "goods_list":goods_list,
        "title":"用户中心",
        "active":"info"
    }
    return render(request,"user/user_center_info.html",context)

@login_required
def all_order(request,page_num):
    """全部订单"""
    # 查询当前登陆用户所有的订单信息
    user_id = request.session["user_id"]
    all_order = OrderModel.objects.filter(user_id = user_id)
    # 每一页展示2个
    paginator = Paginator(all_order,2)
    page = paginator.page(page_num)

    context = {
        "page":page,
        "page_num":page_num,
        "title":"全部订单",
        "active":"all_order"
    }
    return render(request,"user/user_center_order.html",context)

def upload(request):
    """上传文件"""
    myfile = request.FILES.get(" myfile")
    if request.method == "GET":
        return render(request,"upload.html")
    if request.method == "POST":
        ext = myfile.name.split(".")[-1]
        filename = "test"+ ext
        with open("a.text","wb")as fp:
            for chunk in myfile.chunks():
                fp.write(chunk)
            return JsonResponse({"result":"success"})